package com.zlx.xbhy.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.zlx.xbhy.config.AliyunOOS;
import com.zlx.xbhy.entity.Result;
import com.zlx.xbhy.entity.User;
import com.zlx.xbhy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName ImgController
 * @Description 图片上传类
 * @Author Edward
 * @Date 2020/11/21 22:45
 */
@RestController
@RequestMapping("/img/")
public class ImgController {
    @Autowired
    private UserService userService;

    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunOOS aliyunConfig;

//    @PostMapping(value = "upload/{id}",consumes = { "multipart/mixed", "multipart/form-data" })
    public Result upload(@RequestParam("upfile") MultipartFile upfile,@PathVariable Long id){
        //获取图片名字和后缀
        String fileName = upfile.getOriginalFilename();
        //获取图片后缀
        String type = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        fileName = uuid + "." + type;
        try {
            upfile.transferTo(new File("D:\\nginx-1.16.1\\html\\uploads\\"+fileName));
            User user = new User();
            user.setId(id);
            //地址映射
            user.setPic("http://localhost/uploads/"+fileName);
            //保存新的图片地址
            userService.updateByPrimaryKeySelective(user);
        }catch (Exception e){
            return new Result(false,"文件上传失败",null);
        }
        return new Result(true,"文件上传成功！","http://localhost/uploads/"+fileName);
    }

    @PostMapping(value = "upload/{id}",consumes = { "multipart/mixed", "multipart/form-data" })
    public Result uploadAliyun(@RequestParam("upfile") MultipartFile upfile,@PathVariable Long id){
        //获取图片名字和后缀
        String fileName = upfile.getOriginalFilename();
        //获取图片后缀
//        String type = fileName.substring(fileName.lastIndexOf("."));
        String type=null;
        boolean isLegal = false;
        for (String types : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(upfile.getOriginalFilename(), types)) {
                isLegal = true;
                type=types;
                break;  // 只要与允许上传格式其中一个匹配就可以
            }
        }
        if (!isLegal) {
            return new Result(false,"图片上传格式不正确！！！",null);
        }
        // 2. 准备上传API的参数
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        fileName = uuid  + type;

        // 3. 上传至阿里OSS
        try {
            PutObjectResult putObjectResult = ossClient.putObject(aliyunConfig.getBucketName(), fileName, new ByteArrayInputStream(upfile.getBytes()));
            User user = new User();
            user.setId(id);
            //地址映射
            user.setPic(aliyunConfig.getUrlPrefix()+fileName);
            //保存新的图片地址
            userService.updateByPrimaryKeySelective(user);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,"文件上传失败",null);
        }

//        try {
//            upfile.transferTo(new File("D:\\nginx-1.16.1\\html\\uploads\\"+fileName));
//            User user = new User();
//            user.setId(id);
//            //地址映射
//            user.setPic("http://localhost/uploads/"+fileName);
//            //保存新的图片地址
//            userService.updateByPrimaryKeySelective(user);
//        }catch (Exception e){
//            return new Result(false,"文件上传失败",null);
//        }
        return new Result(true,"文件上传成功！",aliyunConfig.getUrlPrefix()+fileName);
    }
}
